<template>
  <div class="login">
    <el-menu
      :default-active="activeIndex"
      style="display: flex; justify-content: space-between; background-color: rgb(12 12 12 / 20%)"
      text-color="#fff"
      mode="horizontal"
      @select="handleSelect"
    >
      <img src="../assets/images/logo.png" alt="Logo" style="margin-left: 10%" />
      <div style="display: flex">
        <el-menu-item index="1">首页</el-menu-item>
        <!-- <el-menu-item index="2">登录</el-menu-item> -->
        <el-menu-item index="3">产品</el-menu-item>
        <el-menu-item index="4">关于我们</el-menu-item>
      </div>
    </el-menu>
    <div v-if="product" style="height: 100%">
      <img src="../assets/images/1.jpg" style="width: 100%; height: 100%" />
      <img src="../assets/images/2.jpg" style="width: 100%; height: 100%" />
      <img src="../assets/images/3.jpg" style="width: 100%; height: 100%" />
      <img src="../assets/images/4.jpg" style="width: 100%; height: 100%" />
      <img src="../assets/images/5.jpg" style="width: 100%; height: 100%" />
      <img src="../assets/images/6.jpg" style="width: 100%; height: 100%" />
    </div>
    <div style="background-color: rgb(12 12 12 / 60%); width: 647px; height: 550px; position: absolute; left: 35%; top: 10%" v-if="isVisible">
      <div style="margin: 40px">
        <div style="color: #fff; margin-bottom: 10px; font-size: 25px; margin-left: 40%">关于我们</div>
        <div style="color: #fff; font-size: 18px">
          <div style="margin-bottom: 20px; text-indent: 2em; line-height: 1.5em">
            南京共识信息科技有限公司成立于2019年5月，是一家以人工智能与区块链技术为核心驱动力的高新技术企业，专注于智能化系统研发与数字化转型解决方案的创新实践。公司立足南京，辐射全国，依托自主研发的核心软件系统，在数字内容生产、金融科技服务、可信电商平台等领域构建起完整的技术生态体系，为全国中小企业、金融机构、个人消费者提供多维度、全方位数字化和智能化的一站式服务。
          </div>
          <div style="margin-bottom: 20px; text-indent: 2em; line-height: 1.5em">
            公司独创的"AI+Blockchain"双引擎架构，实现了人工智能与区块链技术的深度耦合。拥有电商商城B2B2C平台、金融服务SaaS平台、汽车服务SaaS平台等多个产品。此外，公司还提供直播运营、电商运营、短视频制作等多项服务。
          </div>
          <div style="margin-bottom: 20px; text-indent: 2em; line-height: 1.5em">
            南京共识始终秉承"技术创造共识，智能连接未来"的企业使命，通过持续的技术创新与场景深耕，致力于成为智能经济时代的数字化转型赋能者。在人工智能与区块链技术深度融合的新赛道上，公司将持续输出创新价值，与合作伙伴共建可信、智能的数字经济新生态。
          </div>
        </div>
      </div>
    </div>
    <div class="loginform">
      <div style="color: #fff; margin-left: 10%; width: 36%" v-if="Home">
        <div style="margin-bottom: 20px; font-size: 45px">共识数字人</div>
        <div style="font-size: 25px">
          共识数字人融合人工智能与实时渲染技术，通过声音定制、形象定制、视频合成,
          智能交互等能力，来帮您构建智能的、有情感的、可交互的智能数字人分身，助 您开启全新的数字化时代。
        </div>
      </div>
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form" v-if="loginR">
        <img src="../assets/images/logo.png" alt="Logo" style="width: 100px" />
        <h3 class="title">Welcome to GS</h3>
        <!-- <el-form-item v-if="tenantEnabled" prop="tenantId">
        <el-select v-model="loginForm.tenantId" filterable placeholder="请选择/输入公司名称" style="width: 100%">
          <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
          <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
        </el-select>
      </el-form-item> -->
        <!-- <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item> -->
        <!-- <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码" @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item> -->
        <!-- <el-form-item v-if="captchaEnabled" prop="code">
        <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item> -->
        <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox> -->
        <!-- <el-form-item style="float: right">
        <el-button circle title="微信登录" @click="doSocialLogin('wechat')">
          <svg-icon icon-class="wechat" />
        </el-button>
        <el-button circle title="MaxKey登录" @click="doSocialLogin('maxkey')">
          <svg-icon icon-class="maxkey" />
        </el-button>
        <el-button circle title="TopIam登录" @click="doSocialLogin('topiam')">
          <svg-icon icon-class="topiam" />
        </el-button>
        <el-button circle title="Gitee登录" @click="doSocialLogin('gitee')">
          <svg-icon icon-class="gitee" />
        </el-button>
        <el-button circle title="Github登录" @click="doSocialLogin('github')">
          <svg-icon icon-class="github" />
        </el-button>
      </el-form-item> -->
        <el-form-item prop="phonenumber">
          <el-input v-model="loginForm.phonenumber" type="text" size="large" auto-complete="off" placeholder="请输入11位手机号码"> </el-input>
        </el-form-item>
        <el-form-item prop="checkPhoneCode">
          <div style="width: 100%; display: flex; justify-content: space-between">
            <el-input style="width: 65%" v-model="loginForm.smsCode" type="text" size="large" auto-complete="off" placeholder="请输入6位验证码">
            </el-input>
            <el-button type="primary" size="large" @click="sendVerificationCode" :disabled="isSendingCode || countdown > 0">
              {{ countdown > 0 ? `重新发送(${countdown})` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div v-if="register" style="float: right">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
      <!--  底部  -->
      <div class="el-login-footer">
        <span>Copyright © 2024-2025 共识科技版权所有 | 苏ICP备2025169184号-1</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import Axios from '@/api/axios';
import { getCodeImg, getTenantList, CAPTCHA } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { ref } from 'vue';

const userStore = useUserStore();
const router = useRouter();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  // username: 'admin',
  // password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: '',
  phonenumber: '',
  smsCode: ''
} as LoginData);

// 验证手机号是否合法
var checkMobile = (rules, value, callback) => {
  const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
  if (regMobile.test(value) == true) {
    return callback();
  } else {
    callback(new Error('请输入合法的手机号'));
  }
};
// 验证输入的手机号验证码是否和存储的验证码相同
var checkPhoneCode = (rules, value, callback) => {
  if (value == loginForm.contenttext) {
    return callback();
  } else {
    callback(new Error('验证码错误'));
  }
};

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
  phonenumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: checkMobile, trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入手机验证码', trigger: 'blur' },
    { validator: checkPhoneCode, trigger: 'blur' }
  ]
};

const Home = ref(true);
const isVisible = ref(false);
const loginR = ref(false);
const product = ref(false);
const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

let isSendingCode = ref(true);
let countdown = ref(0);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

/**
 * 获取验证码
 */
const sendVerificationCode = async () => {
  const res = await CAPTCHA(loginForm._rawValue.phonenumber);
  console.log(res);
  if (res.code == 200) {
    isSendingCode.value = true;
    // 设置倒计时时间，这里假设为10秒
    countdown.value = 60;
    // 倒计时效果
    const countdownInterval = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(countdownInterval);
        isSendingCode.value = false;
      }
    }, 1000);
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};
const handleSelect = (key, keyPath) => {
  if (key == 1) {
    Home.value = true;
    loginR.value = false;
    product.value = false;
    isVisible.value = false;
  } else if (key == 2) {
    loginR.value = true;
    Home.value = true;
    product.value = false;
    isVisible.value = false;
  } else if (key == 3) {
    product.value = true;
    loginR.value = false;
    Home.value = false;
    isVisible.value = false;
  } else if (key == 4) {
    isVisible.value = true;
    product.value = false;
    loginR.value = false;
    Home.value = false;
  }
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.el-menu-item:hover {
  background-color: rgb(12 12 12 / 40%) !important; /* 修改为自定义颜色 */
  color: #ffffff !important; /* 修改文字颜色 */
}
.login {
  background-image: url('../assets/images/login-background.png');
  background-size: cover;
  height: 100%;
}

.loginform {
  display: flex;
  align-items: center;
  height: 100%;
}

.title {
  margin: 5px auto 15px auto;
  /* text-align: center; */
  color: #707070;
  font-size: 35px;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  margin-left: 30%;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
